<template>
  <div class="w-[500px] h-[300px] m-auto p-8 bg-gray-100 rounded-lg shadow-md">
    <h2 class="text-2xl font-bold mb-6 text-center">用户登录</h2>

    <Form ref="formRef" :rules="formRules" :model-value="formData" @submit="handleSubmit">
      <div class="mb-4">
        <label class="block mb-2 font-medium">用户名</label>
        <Input class="input" name="username" v-model="formData.username" />
      </div>

      <div class="mb-4">
        <label class="block mb-2 font-medium">密码</label>
        <Input class="input" name="password" v-model="formData.password" />
      </div>

      <div class="mt-6 flex gap-4">
        <button type="submit" class="w-[80px] h-[30px] btn bg-blue-500 text-white px-4  rounded hover:bg-blue-600">
          登录
        </button>
        <button type="button" class="w-[80px] btn h-[30px]  bg-gray-500 text-white px-4  rounded hover:bg-gray-600"
          @click="handleReset">
          重置
        </button>
      </div>
    </Form>

    <div v-if="isLoading && userInfo.username">
      <Loading></Loading>
    </div>

    <div v-if="isError">
      请求出错
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, reactive } from 'vue';
import Input from '../components/Input.vue'
import Form from '../components/Form.vue'
import { useLogin } from '../hooks/user'
// 表单引用
const formRef = ref<InstanceType<typeof Form> | null>(null);




// 表单数据
const formData = reactive({
  username: '',
  password: ''
});

const userInfo = ref({ username: '', password: '' })
const { refetch, data, isLoading, isError } = useLogin(() => userInfo.value); // 提交事件里面 
console.log(data, isLoading, isError, '登录按钮');
// 表单校验规则
const formRules = [
  {
    name: 'username',
    trigger: 'Blur',
    type: 'Required',
    errorMsg: '用户名不能为空！'
  },

  {
    name: 'password',
    trigger: 'Blur',
    type: 'Required',
    errorMsg: '密码不能为空！'
  }
];


// 处理表单提交
const handleSubmit = async (formData: any, isValid: boolean) => {
  if (isValid) {
    console.log('表单校验通过，准备提交:', formData);
    // 这里可以添加实际的登录逻辑 ,调用接口，进行登录操作
    // 自定义组合式函数， 只能放在setup函数里面调用
    userInfo.value = formData; // 更新用户表单
    await refetch();// 让接口重新执行；
    console.log(data, isLoading, isError, '登录按钮');
  } else {
    console.log('表单校验失败，请检查输入');
  }
};

// 手动触发校验
// const handleLogin = () => {
//   if (formRef.value) {
//     const isValid = formRef.value.validate();
//     if (isValid) {
//       console.log('登录校验通过:', formData);


//     } else {
//       console.log('登录校验失败');
//     }
//   }
// };

// 重置表单
const handleReset = () => {
  formData.username = '';
  formData.password = '';
  // 重置校验状态
  if (formRef.value) {
    // 可以在这里添加重置校验状态的逻辑
  }
};
</script>
<style scoped></style>